var mWaiting;
var mChallenges;
var mModal;
var mChallengedPlayer;

var interval_waiting;
var interval_challenge;
var interval_accepted;
var interval_countdown;

var ctr_countdown = 4;

$(function(){
	$.ajaxSetup({cache: false});
	startInterval('waiting', 1000);
	startInterval('challenge', 1000);
	initModal();
});

function startInterval(key, milis, data=null){
	if(key == 'waiting'){
		interval_waiting = setInterval(function(){
			get_all_waiting();
		}, milis);
	}
	else if(key == 'challenge'){
		interval_challenge = setInterval(function(){
			get_challenge();
		}, milis);
	}
	else if(key == 'accepted'){
		interval_accepted = setInterval(function(){
			get_challenge_accpeted(mChallengedPlayer);
		}, milis);
	}
	else if(key == 'countdown'){
		ctr_countdown = 6;
		interval_accepted = setInterval(function(){
			if(--ctr_countdown == 0){
				mModal.open({
				content:
				'<h1>Challenge Accepted!</h1>' + 
				'<p>Let the battle begin!...</p>',
				hideClose: true
				});
			}
			else if(ctr_countdown > -1){
				show_countdown(ctr_countdown, data['player_name']);
			}
			else{
				clearInterval(interval_countdown);
				startBattle(data['id'], data['player_name'], 1);
			}
		}, milis);
	}
}

function show_countdown(ctr, player_name){
	mModal.open({
		content:
		'<h1>Challenge Accepted!</h1>' + 
		'<p>Your battle with <strong>' + player_name  + '</strong> will start in ' + ctr + '...</p>',
		hideClose: true
		});
}

function get_challenge(){
	$.ajax({
		url: BASE_URL + 'game/get_challenge',
		data: "",
		dataType: 'json',
		success: function(data){
			if(data != ''){
				mModal.open({
					content:
					'<h1>Here Comes A New Challenger!</h1>' + 
					'<p>You are challenged by <strong>' + data['player_name']  + '</strong> to a battle.</p>' + 
					'<button onclick="startBattle(' + data['id'] + ', \'' + data['player_name'] + '\', 0)">Begin Battle!</button>&nbsp&nbsp' + 
					'<button onclick="denyChallenge()">Deny Challenge</button>',
					hideClose: true
					});
			}
		}
	});
}

function get_challenge_accpeted(challengedPlayer){
	$.ajax({
		url: BASE_URL + 'game/get_challenge_accepted/' + challengedPlayer['id'],
		data: "",
		dataType: 'json',
		success: function(data){
			if(data == 1){
				clearInterval(interval_accepted);
				startInterval('countdown', 1000, challengedPlayer);
			}
			else if(data == 0){
				mModal.open({content:
					'<h1>Challenge Denied!</h1>' + 
					'<p><strong>' + challengedPlayer['player_name']  + '</strong> just denied your challenge.</p>'
					});

				clearInterval(interval_accepted);

				startInterval('waiting', 1000);
				startInterval('challenge', 1000);

			}
			else{
				$("#tbl-player")[0].innerHTML = 'Waiting for <strong>' + challengedPlayer['player_name'] +
					'</strong> to confirm your challenge.';
			}
		}
	});
}

function get_all_waiting(){
	$.ajax({
		url: BASE_URL + 'game/get_all_waiting',
		data: "",
		dataType: 'json',
		success: function(data){
			if(data.length > 0){
				$("#tbl-player")[0].innerHTML = 
					'<th>Player</th>' + 
					'<th>Rank</th>' + 
					'<th></th>'
				;

				for(var idx in data){
					$("#tbl-player")[0].innerHTML += 
						'<tr>' +
							'<td>' + data[idx]['player_name'] + '</td>' + 
							'<td>Noobs</td>' + 
							'<td><a onclick="set_challenge(' + data[idx]['id'] + ')">Challenge!</a></td>' +  
						'</tr>'
					;
				}
			}
			else{
				$("#tbl-player")[0].innerHTML = 'No Players are currently logged in.';
			}
			
			mWaiting = data;
		}
	});
}

function getIndexOf(haystack, needle, field){
	for(var idx in haystack){
		if(haystack[idx][field] == needle){
			return idx;
		}
	}
	return -1;	
}

function set_challenge(id){
	$.ajax({
		url: BASE_URL + 'game/set_challenge/' + id,
		data: "",
		dataType: 'json',
		success: function(data){
			mChallengedPlayer = mWaiting[getIndexOf(mWaiting, id, 'id')];
			var challengedPlayer = mChallengedPlayer['player_name'];
			if(data){
				$.ajax({
					url: BASE_URL + 'game/unset_waiting/' + id + '/' + MY_ID,
					data: "",
					dataType: 'json',
					success: function(data){
						clearInterval(interval_waiting);
						clearInterval(interval_challenge);

						startInterval('accepted', 1000);

						mModal.open({content:
							'<h1>Challenge Sent!</h1>' + 
							'<p>You just challenged <strong>' + challengedPlayer  + '</strong> to a battle.</p>'
							});
					}
				});
			}
			else{
				mModal.open({content:
					'<h1>Challenge Denied!</h1>' + 
					'<p><strong>' + challengedPlayer  + '</strong> is currently challenged by other players.</p>'
					});
			}
		}
	});
}

function denyChallenge(){
	$.ajax({
		url: BASE_URL + 'game/unset_challenge',
		data: "",
		dataType: 'json',
		success: function(data){
			mModal.close();
		}
	});
}

function startBattle(oponent_id, oponent_name, is_mechallenger){
	window.location.href = BASE_URL + 'game/start_battle/' + oponent_id + '/' + oponent_name + '/' + is_mechallenger;
}

function initModal(){
	mModal = (function(){
	    var 
	    method = {},
	    $overlay,
	    $modal,
	    $content,
	    $close;

	    // Append the HTML
	    $overlay = $('<div id="modal-overlay"></div>');
		$modal = $('<div id="modal"></div>');
		$content = $('<div id="modal-content"></div>');
		$close = $('<a id="modal-close" href="#">close</a>');

		$modal.hide();
		$overlay.hide();
		$modal.append($content, $close);

		$(document).ready(function(){
		    $('body').append($overlay, $modal);
		});

	    // Center the modal in the viewport
	    method.center = function () {
		    var top, left;

		    top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
		    left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;

		    $modal.css({
		        top:top + $(window).scrollTop(), 
		        left:left + $(window).scrollLeft()
		    });
		};

	    // Open the modal
	    method.open = function (settings) {
		    $content.empty().append(settings.content);
		    
		    if(settings.hideClose){
		    	$close.hide();
		    }
		    else{
		    	$close.show();
		    }

		    $modal.css({
		        width: settings.width || 'auto', 
		        height: settings.height || 'auto'
		    })

		    method.center();

		    $(window).bind('resize.modal', method.center);

		    $modal.show();
		    $overlay.show();
		};

	    // Close the modal
	    method.close = function () {
		    $modal.hide();
		    $overlay.hide();
		    $content.empty();
		    $(window).unbind('resize.modal');
		};

		$close.click(function(e){
		    e.preventDefault();
		    method.close();
		});

		// $overlay.click(function(e){
		// 	e.preventDefault();
		//     method.close();
		// });

	    return method;
	}());
}